var platform = /(Win|Mac|Linux|iPhone)/.exec(navigator.platform)[0];
if (jQuery.browser.mozilla){
	var agent_version = parseFloat(/Firefox\/(.+)/.exec(navigator.userAgent)[1]);
}else{
	var agent_version = parseFloat(jQuery.browser.version);	
}

function ie6(){
	if(jQuery.browser.msie && (jQuery.browser.version <= 6)){return true;};
	return false;	
}

$(document).ready(function(){	  
	imgLoader = new Image(); 
	imgLoader.src = "/images/progress_bar.gif";
/*	thickbox_init('a.thickbox');*/
	
});

function play_video(file_path){
  var so = new SWFObject('/mediaplayer/mediaplayer.swf','','480','360','8');
  so.addParam('allowscriptaccess','always');
  so.addParam('allowfullscreen','true');
  so.addVariable('file',file_path);
  so.addVariable('width','480');
  so.addVariable('height','360');
  so.addVariable('enablejs','true');
  so.addVariable('autostart','true');
  so.write('video_container');
}

// START - RESTFUL AJAX  
var AJAX_ACTIONS = ['delete', 'put', 'post', 'get'];
var AJAX_ERROR_MSG = "<div id='error'>Unable to load light box at this time.</div>";

jQuery.ajaxSetup({ // NOTE: if you use any of the following callbacks in an AJAX call it will OVERRIDE these
  	beforeSend: function(xhr) {
		xhr.setRequestHeader("Accept", "text/javascript");
		if(tb_is_open()){ 
			$('#TB_load').show(); 
			//$('#TB_status').html("");	
		};
	},
	timeout: 8000,
	error: function(){ 
		if(tb_is_open()){ $("#TB_status").html(AJAX_ERROR_MSG); } else { $("#flash_container").html(AJAX_ERROR_MSG); }
	},
	complete: function(){
		if(tb_is_open()){ 
			$('#TB_load').hide(); 
			thickbox_init("#TB_ajaxContent a.thickbox"); 
			$("#TB_window").css({display:"block"}); 
		}
	}
})

function tb_is_open(){
		if($('#TB_window')[0] != null){	return true; };
		return false;
}

function restful_ajax(method, path){
	var target_element = $('#TB_window');	
	var width = $('#TB_ajaxContent').width();
	var height = $('#TB_ajaxContent').height();
	var caption = $('#TB_ajaxWindowTitle').text();
	
	if(jQuery.inArray(method.toLowerCase(), AJAX_ACTIONS) < 0){ return false; }	
	if(jQuery.browser.msie && (jQuery.browser.version <= 8)){// TODO: check to see if ie 8 supports delete and put??
		path = path + "?_method="+method;
		method = 'post';
	};
	
		$.ajax({
			url: path,
			type: method,
			contentType: 'text/javascript',
		 	dataType: 'html',	
			success: function(html){
				target_element.html(html);
				thickbox_resize(width, height);
				$('#TB_ajaxWindowTitle').text(caption);
			}
		});
	
	return false;
}

function ajaxify_message_forms(messages_array){

	$.each(messages_array, function(i, n){
		$('#new_message_form_' + n).submit(function(){
			var width = $('#TB_ajaxContent').width();
			var height = $('#TB_ajaxContent').height();
			var caption = $('#TB_ajaxWindowTitle').text();
			$('#TB_load').show();
			
				$('#TB_window').hide();//fadeOut("normal", function(){ 			
				$('#new_message_form_' + n).ajaxSubmit({
					success: function(html){
						$('#TB_load').hide(); 							
						$('#TB_window').html(html);	
						thickbox_resize(width, height);	
						$('#TB_ajaxWindowTitle').text(caption);						
						$('#TB_window').show();	
					}
				});	
			
			return false;
		});
	});
}

function thickbox_init(domChunk){
	$(domChunk).click(function(){
		$("#flash_container").html("&nbsp;");//remove any flash messages before loading a lightbox		
		var caption = this.title || this.name || null;
		var url = this.href || this.alt;
		thickbox_show(caption, url);	
		this.blur();
		return false;
	});
}

function thickbox_resize(width, height){
	$("#TB_title_tr").width((width+3));
	$("#TB_ajaxWindowTitle").width((width-61));
	$("#TB_ajaxContent").css({'width': width+'px', 'height': height+'px'});		
	$("#TB_footer_br").width((width+3));
}

function thickbox_show(caption, url) {
	try {
		if (ie6()) {//if IE 6 :: typeof document.body.style.maxHeight === "undefined"		
			$("body","html").css({height: "100%", width: "100%"});
			$("html").css("overflow","hidden");
			if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6
				$("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>");
				$("#TB_overlay").click(thickbox_remove);
			}
		}else{//all other browsers
			if(document.getElementById("TB_overlay") === null){
				$("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>");
				$("#TB_overlay").click(thickbox_remove);
			}
		}

		if(thickbox_detectMacXFF()){
			if(jQuery.browser.mozilla && (agent_version < 3) && (platform == 'Mac')){
				$('#family_tree').css('visibility','hidden');
			}
			$("#TB_overlay").addClass("TB_overlayMacFFBGHack");//use png overlay so hide flash
		}else{			
			$("#TB_overlay").addClass("TB_overlayBG");//use background and opacity			
		}

		if($("#TB_load")[0] == null){ $("body").append("<div id='TB_load'><img src='"+imgLoader.src+"' /></div>"); }//add loader to the page
		$('#TB_load').show();//show loader

		var baseURL;
	    if(url.indexOf("?")!==-1){ //if there is a query string involved
			baseURL = url.substr(0, url.indexOf("?"));
	    }else{ 
	   		baseURL = url;
	    }
		
		var queryString = url.replace(/^[^\?]+\??/,'');
		var params = thickbox_parseQuery( queryString );
		if(caption===null){caption="";}		
		
		window_height = get_page_size()[1];		
		tb_height_default = window_height - 80;
		if(tb_height_default < 540){ tb_height_default = 540; }
		if(tb_height_default > 600){ tb_height_default = 600; }		
		
		caption = params['title_override'] || caption;		
		TB_WIDTH = (params['width']*1) + 30 || 970; 
		TB_HEIGHT = (params['height']*1) + 45 || tb_height_default;		

		ajaxContentW = TB_WIDTH - 30;
		ajaxContentH = TB_HEIGHT - 45;
		
		if($("#TB_window").css("display") != "block"){// new thickbox window	
			$('#flash_container').html('&nbsp;');//clear navigation flash to avoid duplicate DOM ID's 					
			if(params['modal'] != "true"){
				$("#TB_window").html("");//clear any existing content			
			}else{//modal
				$("#TB_overlay").unbind();
				$("#TB_window").append("<div id='TB_ajaxContent' class='TB_modal' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px;'></div>");	
			}
		}else{//this means the window is already up, we are just loading new content via ajax for thick box calls from with-in a thickbox
			$('#TB_window').hide();
			//$("#TB_ajaxContent")[0].scrollTop = 0;				
		}
		
		$.ajax({
			url: url,
			dataType: 'html',
			success: function(html){
				$("#TB_load").hide();
				$("#TB_window").html(html);			
				if(caption){
					if($('#preferences_notice')[0] == null){
						$('#TB_ajaxWindowTitle').text(caption);
					}
				};
				thickbox_resize(ajaxContentW, ajaxContentH);				
				thickbox_position();				
				$('#TB_window').show();				
				if(ie6()){ie6_button_hover('TB_close');};			
				$("#TB_close_button").click(thickbox_remove);					
			}
		});
		
		if(!params['modal']){
			document.onkeyup = function(e){ 	
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if(keycode == 27){ // close
					thickbox_remove();
				}	
			};
		}

	} catch(e) {
		//nothing here
	}
}

function thickbox_remove() {
 	$("#TB_imageOff").unbind("click");
	$("#TB_closeWindowButton").unbind("click");
	if(jQuery.browser.mozilla && (agent_version < 3) && (platform == 'Mac')){ //Firefox2 OSX 			
		$('#TB_window, #TB_overlay, #TB_HideSelect').unbind().remove();
		$('#family_tree').css('visibility','visible');
	}else{
		$("#TB_window").fadeOut("fast",function(){$('#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove();});		
	}
	$("#TB_load").remove();
	if (ie6()) {
		$("body","html").css({height: "auto", width: "auto"});
		$("html").css("overflow","");
	}
	document.onkeydown = "";
	document.onkeyup = "";
	return false;
}

function thickbox_parseQuery ( query ) {
   var Params = {};
   if ( ! query ) {return Params;}// return empty object
   var Pairs = query.split(/[;&]/);
   for ( var i = 0; i < Pairs.length; i++ ) {
      var KeyVal = Pairs[i].split('=');
      if ( ! KeyVal || KeyVal.length != 2 ) {continue;}
      var key = unescape( KeyVal[0] );
      var val = unescape( KeyVal[1] );
      val = val.replace(/\+/g, ' ');
      Params[key] = val;
   }
   return Params;
}

function thickbox_position() {
	$("#TB_window").css({marginLeft: '-' + parseInt((TB_WIDTH / 2),10) + 'px', width: TB_WIDTH + 'px'});
	if ( !(ie6())) { // take away IE6 ::jQuery.browser.msie && jQuery.browser.version < 7
		$("#TB_window").css({marginTop: '-' + (parseInt((TB_HEIGHT / 2),10)+20) + 'px'});
	}
}

function get_page_size() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
	arrayPageSize = [myWidth, myHeight];
	return arrayPageSize;
}

function thickbox_detectMacXFF() {
  var userAgent = navigator.userAgent.toLowerCase();
  if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
    return true;
  }
}
